/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mavenrentcars.controller;

import com.mavenrentcars.exception.ViewException;
import com.mavenrentcars.form.OrderForm;
import com.mavenrentcars.model.Car;
import com.mavenrentcars.model.Place;
import com.mavenrentcars.model.Reservation;
import com.mavenrentcars.service.AccountService;
import com.mavenrentcars.service.CarService;
import com.mavenrentcars.service.PlaceService;
import com.mavenrentcars.service.RatingService;
import com.mavenrentcars.service.ReservationService;
import com.mavenrentcars.validator.Validator;
import com.mavenrentcars.validator.impl.OrderValidator;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author serg
 */
@Controller
public class OrderController {

    @Autowired
    AccountService accountService;
    @Autowired
    CarService carService;
    @Autowired
    PlaceService placeService;
    @Autowired
    ReservationService reservationService;
    @Autowired
    RatingService ratingService;

    @RequestMapping(value = "order_view.htm", method = RequestMethod.GET)
    public ModelAndView item(
            HttpServletResponse httpServletResponse,
            @RequestParam(value = "id", required = true) int id) {
        ModelAndView mav = new ModelAndView("order/item");
        mav.addObject("acc", accountService);
        try {
            Car item = carService.get(id);
            mav.addObject("item", item);

            Set<Place> places = item.getPlaces();
            mav.addObject("places", places);

            List<Reservation> reservations = reservationService.getAll(item);
            mav.addObject("reservations", reservations);

            boolean vote = ratingService.isVote(item, accountService.getLoggedInAccount());
            mav.addObject("vote", vote);

            if (reservations != null) {
                String json_days = reservationService.getJasonByCarDays(item);
                mav.addObject("json_days", json_days);
            } else {
                mav.addObject("json_days", "{}");
            }


        } catch (ViewException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        }

        mav.addObject("res", true);
        return mav;
    }

    @RequestMapping(value = "order_add.htm", method = RequestMethod.POST)
    public ModelAndView add(
            HttpServletResponse httpServletResponse,
            @RequestParam(value = "data", required = true) String data) {

        ObjectMapper mapper = new ObjectMapper();
        ModelAndView mav = new ModelAndView("jsonView");

        OrderForm form;
        try {
            form = mapper.readValue(data, OrderForm.class);
            Validator valid = new OrderValidator(form);
            if (!valid.validation()) {
                mav.addObject("res", false);
                mav.addObject("errors", valid.getErrors());
                return mav;
            }

            Reservation item = reservationService.add(form);

            boolean vote = ratingService.isVote(item.getCar(), item.getUser());
            if (!vote && !form.getRating().equals("")) {
                ratingService.set(item.getCar(), item.getUser(), Integer.parseInt(form.getRating()));
            }

            mav.addObject("res", true);
            mav.addObject("item", item.getCar().getId());

        } catch (ViewException ex) {
            mav.addObject("error", ex.getMessage());
            mav.addObject("res", false);
        } catch (JsonGenerationException ex) {
            mav.addObject("error", ex.getMessage());
            mav.addObject("res", false);
        } catch (JsonMappingException ex) {
            mav.addObject("error", ex.getMessage());
            mav.addObject("res", false);
        } catch (IOException ex) {
            mav.addObject("error", ex.getMessage());
            mav.addObject("res", false);
        }
        return mav;
    }

    @RequestMapping(value = "car_orders_list.htm", method = RequestMethod.GET)
    public ModelAndView carOrders(
            HttpServletResponse httpServletResponse,
            @RequestParam(value = "id", required = true) int id) {

        ModelAndView mav = new ModelAndView("order/list");
        try {
            Car item = carService.get(id);
            List<Reservation> list = reservationService.getAll(item);
            mav.addObject("list", list);
        } catch (Exception ex) {
            Logger.getLogger(CarController.class.getName()).log(Level.SEVERE, null, ex);
        }
        mav.addObject("acc", accountService);
        return mav;
    }

    @RequestMapping(value = "my_orders_list.htm", method = RequestMethod.GET)
    public ModelAndView userOrders(
            HttpServletResponse httpServletResponse) {

        ModelAndView mav = new ModelAndView("order/list");
        try {
            List<Reservation> list = reservationService.getAll(accountService.getLoggedInAccount());
            mav.addObject("list", list);
        } catch (Exception ex) {
            Logger.getLogger(CarController.class.getName()).log(Level.SEVERE, null, ex);
        }
        mav.addObject("acc", accountService);
        return mav;
    }
}
